<template>
    <Panel title="projects" >
        <div 
            class="mt-2 project "
            v-for="project in projects" 
            :key="project.id"
            :class="{green: currentProject !=null && project.id === currentProject.id }"
        >   
            <EditableRecord
                :isEditMode="!project.isEditMode"
                :title="project.title"
                @onInput="setProjectTitle({
                    project,
                    title: $event,
                })"
                @onClick="projectClicked(project)"
                @onEdit="setEditMode(project)"
                @onSave="saveProject(project)"
                @onDelete="deleteProject(project)"
            >
            </EditableRecord>    
        </div>
        <CreateRecord 
            placeholder="My Project name ..."
            :value="newProjectName"
            @onInput="setNewProjectName"
            @create="createProject"
        >
        </CreateRecord>   
        <v-alert type="error" :value="deleteError">
            {{deleteError}}
        </v-alert>
    </Panel> 
</template>
<script>
import { mapMutations, mapState, mapActions } from 'vuex';
import CreateRecord from '@/components/CreateRecord.vue';
import EditableRecord from '@/components/EditableRecord.vue';

export default {
    computed: {
        ...mapState('projects',[
            'newProjectName',
            'projects',
            'deleteError',
            'currentProject',
        ]),
    },
    components: {
        CreateRecord,
        EditableRecord,
    },
    methods: {
        projectClicked(project){
            this.setCurrentProject(project);
            this.fetchTasksForProject(project)
        },
        ...mapMutations('projects',[
            'setNewProjectName',
            'setEditMode',
            'unsetEditMode',
            'setProjectTitle',
            'setCurrentProject',
        ]),
        ...mapActions('projects', [
            'createProject',
            'fetchProjects',
            'saveProject',
            'deleteProject',
        ]),
        ...mapActions('tasks', [
            'fetchTasksForProject',
        ])
    },
    mounted() {
        this.fetchProjects();
    },
}
</script>
<style>
.project {
    font-size: 24px;
}
.icon, span {
    cursor: pointer;
}
.icon:hover {
    color: #000;
}
</style>

 